<template>
  <div class="content">
    <a-form @submit="handleSubmit" style="width:70%;margin:0px auto;" :form="form">
      <a-form-item
        v-bind="formItemLayout"
        label="经营场所照片"
        :help="`支持图片格式JPG、PNG，且每个文件大小不超过${imageSize}M`"
      >
        <div class="clearfix" style="display:inline-block;">
          <a-upload
            v-decorator="['upload3',{rules: [{ required: true, message: '请上传经营场所照片!' }]}]"
            action="/file/file/upload"
            listType="picture-card"
            :data="{to}"
            name="upfile"
            :headers="henderstoken"
            :fileList="fileList1"
            @preview="handlePreview"
            @change="handleChange"
          >
            <div v-if="fileList1.length < 1">
              <a-icon type="plus" />
              <div class="ant-upload-text">门头或前台照</div>
            </div>
          </a-upload>
          <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
            <img alt="example" style="width: 100%" :src="previewImage" />
          </a-modal>
        </div>
        <div class="clearfix" style="display:inline-block;">
          <a-upload
            :data="{to}"
            name="upfile"
            :headers="henderstoken"
            action="/file/file/upload"
            listType="picture-card"
            :fileList="fileList2"
            @preview="handlePreview2"
            @change="handleChange2"
          >
            <div v-if="fileList2.length < 1">
              <a-icon type="plus" />
              <div class="ant-upload-text">办公室内景照</div>
            </div>
          </a-upload>
          <a-modal :visible="previewVisible2" :footer="null" @cancel="handleCancel2">
            <img alt="example" style="width: 100%" :src="previewImage2" />
          </a-modal>
        </div>
      </a-form-item>
      <!-- 其他材料 -->
      <a-form-item
        v-bind="formItemLayout"
        label="其他材料"
        :help="`行业经营许可证等，支持图片格式JPG、PNG，且每个文件大小不超过${imageSize}M`"
      >
        <div class="clearfix">
          <a-upload
            v-decorator="['upload']"
            name="upfile"
            :headers="henderstoken"
            action="/file/file/upload"
            listType="picture-card"
            :fileList="otherfileList"
            :data="{to}"
            @preview="handlePreview3"
            @change="handleChange3"
          >
            <div v-if="otherfileList.length < 5">
              <a-icon type="plus" />
              <div class="ant-upload-text">其他材料</div>
            </div>
          </a-upload>
          <a-modal :visible="previewVisible3" :footer="null" @cancel="handleCancel3">
            <img alt="example" style="width: 100%" :src="previewImage3" />
          </a-modal>
        </div>
      </a-form-item>
      <!-- 授权办理人 -->
      <a-row class="row-sty">
        <a-col :xs="{ span : 24 }" :sm="{ span:9 }" class="formGroupTitle">授权办理人</a-col>
        <a-col :xs="{ span : 24 }" :sm="{ span:12,offset:1 }">
          <p style="font-size:12px;">
            非法定代表人本人申请，请填写授办理人信息，并提供《授权委托书》
            <a
              class="a-sty"
              href="static/授权委托书.docx"
              download="授权委托书.docx"
              target="_blank"
            >下载模板</a>
          </p>
        </a-col>
      </a-row>
      <a-form-item v-bind="formItemLayout" label="姓名">
        <a-input
          style="width:80%;"
          v-decorator="[
                      'identityName',
                      {rules: [{ required: false, message: '请输入姓名' }]}
                    ]"
          placeholder="请输入授权办理人姓名"
        />
      </a-form-item>

      <a-form-item v-bind="formItemLayout" label="证件类型">
        <div>
          <a-select
            style="width:80%;"
            disabled
            v-decorator="[
                      'codetype',
                      {rules: [{ required: false, message: '请选择证件类型' }],initialValue: 'legal'}
                    ]"
          >
            <a-select-option value="legal">身份证</a-select-option>
            <a-select-option value="lucy">护照</a-select-option>
            <a-select-option value="disabled">港澳台通行证</a-select-option>
            <a-select-option value="Yiminghe">军官证</a-select-option>
            <a-select-option value="Yiminghe">户口簿</a-select-option>
          </a-select>
        </div>
      </a-form-item>

      <a-form-item v-bind="formItemLayout" label="证件号码" help="证件号码末位为X的用大写X代替">
        <a-input
          style="width:80%;"
          v-decorator="[
                      'identityNo',
                      {rules: [{ required: false, message: '请输入证件号码' },{
                         validator: validateIdentityNo
                       }],validateTrigger: 'blur'}
                    ]"
          placeholder="请输入证件号码"
        />
      </a-form-item>

      <a-form-item v-bind="formItemLayout" label="证件有效期">
        <a-date-picker
          :disabledDate="disabledDate"
          placeholder="请选择证件有效期"
          @change="dateChange"
          v-decorator="[
                      'expiryDate',
                      {rules: [{ required: false, message: '请选择证件有效期' }]}
                    ]"
          :format="dateFormat"
        />
      </a-form-item>
      <!-- 上传证件-->
      <a-form-item
        v-bind="formItemLayout"
        label="上传证件"
        :help="`支持图片格式JPG、PNG，且每个文件大小不超过${imageSize}M`"
      >
        <div class="clearfix" style="display:inline-block;">
          <a-upload
            v-decorator="['upload2',{rules: [{ required: false, message: '请上传身份证正/反面!' }]}]"
            action="/file/file/upload"
            listType="picture-card"
            :data="{to}"
            name="upfile"
            :headers="henderstoken"
            :fileList="idfileList1"
            @preview="handlePreview4"
            @change="handleChange4"
          >
            <div v-if="idfileList1.length < 1">
              <a-icon type="plus" />
              <div class="ant-upload-text">身份证人像面</div>
            </div>
          </a-upload>
          <a-modal :visible="previewVisible4" :footer="null" @cancel="handleCancel4">
            <img alt="example" style="width: 100%" :src="previewImage4" />
          </a-modal>
        </div>
        <div class="clearfix" style="display:inline-block;">
          <a-upload
            :data="{to}"
            name="upfile"
            :headers="henderstoken"
            action="/file/file/upload"
            listType="picture-card"
            :fileList="idfileList2"
            @preview="handlePreview5"
            @change="handleChange5"
          >
            <div v-if="idfileList2.length < 1">
              <a-icon type="plus" />
              <div class="ant-upload-text">身份证国徽面</div>
            </div>
          </a-upload>
          <a-modal :visible="previewVisible5" :footer="null" @cancel="handleCancel5">
            <img alt="example" style="width: 100%" :src="previewImage5" />
          </a-modal>
        </div>
      </a-form-item>
      <!-- <a-form-item style="text-align:center;"  v-bind="formItemLayout"> -->

      <a-row>
        <a-col
          style="margin-top:20px;margin-bottom:20px;"
          :xs="{ span : 24 }"
          :sm="{ span:12,offset:10}"
        >
          <a-button class="submitButton" type="primary" html-type="submit" :loading="loading">下一步</a-button>
        </a-col>
      </a-row>
      <!-- </a-form-item> -->
    </a-form>
  </div>
</template>
<script>
import {
  Radio,
  Input,
  InputNumber,
  DatePicker,
  Cascader,
} from "ant-design-vue";
import { message } from "ant-design-vue";
import api from "@/common/api";
import { error } from "util";
import { fail } from "assert";
import moment from "moment";
import { mapState } from "vuex";
export default {
  data() {
    return {
      loading: false,
      dateFormat: "YYYY-MM-DD",
      logid: "",
      logms: "",
      id: "",
      pass: false,
      expiryDate: "",
      fileList1: [],
      fileList2: [],
      otherfileList: [],
      idfileList1: [],
      idfileList2: [],
      previewVisible: false,
      previewVisible2: false,
      previewVisible3: false,
      previewVisible4: false,
      previewVisible5: false,
      previewImage: "",
      previewImage2: "",
      previewImage3: "",
      previewImage4: "",
      previewImage5: "",
      docking: true,
      henderstoken: {
        Authorization: localStorage.getItem("token"),
      },
      to:sessionStorage.getItem("memberNo") + "_" + sessionStorage.getItem("username"),
      interiorImg: "",
      doorImg: "",
      otherImg: [],
      imgHead: "",
      imgEmblem: "",

      formItemLayout: {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 9 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 12, offset: 1 },
          md: { span: 10, offset: 1 },
        },
      },
    };
  },
  computed: {
    ...mapState({
      imageSize: (state) => state.imageSize,
    }),
  },
  beforeCreate() {
    this.form = this.$form.createForm(this);
  },
  mounted() {
    console.log(this.$route.query.modify);
    if (this.$route.query.modify) {
      this.logid = JSON.parse(sessionStorage.getItem("logid"));
      if (this.logid) {
        this.form.setFieldsValue({
          identityName: this.logid.identityName,
          identityNo: this.logid.identityNo,
          expiryDate: moment(this.logid.expiryDate),
        });
        this.id = this.logid.id;
        this.expiryDate = this.logid.expiryDate;
        this.imgHead = this.logid.imgHead;
        this.imgEmblem = this.logid.imgEmblem;
        this.idfileList1 = [
          {
            uid: "3",
            name: "xxx.png",
            status: "done",
            url: "/file/file/download/" + this.logid.imgHead,
          },
        ];
        this.idfileList2 = [
          {
            uid: "4",
            name: "xxx.png",
            status: "done",
            url: "/file/file/download/" + this.logid.imgEmblem,
          },
        ];
      } else {
      }
      this.logms = JSON.parse(sessionStorage.getItem("logms"));
      this.form.setFieldsValue({
        upload3: this.logms.doorImg,
      });
      this.interiorImg = this.logms.interiorImg;
      this.doorImg = this.logms.doorImg;
      this.otherImg = this.logms.otherImgs;
      this.fileList1 = [
        {
          uid: "-1",
          name: "xxx.png",
          status: "done",
          url: "/file/file/download/" + this.logms.doorImg,
        },
      ];
      this.fileList2 = [
        {
          uid: "1",
          name: "xxx.png",
          status: "done",
          url: "/file/file/download/" + this.logms.interiorImg,
        },
      ];
      this.otherfileList = [
        // {
        //   uid: "2",
        //   name: "xxx.png",
        //   status: "done",
        //   url: "/file/file/download/" + this.logms.otherImg
        // }
      ];
      if (this.logms.otherImgs) {
        if (this.logms.otherImgs.length > 0) {
          for (var i = 0; i < this.logms.otherImgs.length; i++) {
            let son = {
              uid: this.logms.otherImgs[i],
              name: "xxx.png",
              status: "done",
              url: "/file/file/download/" + this.logms.otherImgs[i],
            };
            this.otherfileList.push(son);
          }
        }
      }
    } else {
      console.log("222");
    }
  },
  created() {
    this.docking = sessionStorage.getItem("docking");
  },
  methods: {
    moment,
    //日期不可选
    disabledDate(current) {
      // Can not select days before today and today
      return current && current < moment().endOf("day");
    },
    handleSubmit(e) {
      e.preventDefault();
      this.form.validateFields((err, values) => {
        if (!err) {
          console.log("values", values);
          if (this.fileList2.length == 0) {
            this.$message.error("请上传办公室内景照");
            return false;
          }
          if (values.identityName && !values.identityNo) {
            this.$message.error("您已填写授权办理人姓名，请填写证件号码！");
            return false;
          }
          if (values.identityName && !values.expiryDate) {
            this.$message.error("您已填写授权办理人姓名，请填写证件有效期！");
            return false;
          }
          if (
            (values.identityName && this.idfileList2.length == 0) ||
            (values.identityName && this.idfileList1.length == 0)
          ) {
            this.$message.error("请上传身份证照片");
            return false;
          }
          this.otherImg = [];
          console.log(this.otherfileList);
          console.log(this.otherImg);
          if (this.otherfileList.length > 0) {
            let len = this.otherfileList.length;
            console.log("len", len);
            for (var i = 0; i < len; i++) {
              console.log(
                "this.otherfileList[i].response",
                this.otherfileList[i].response
              );
              if (this.otherfileList[i].response) {
                this.otherImg.push(this.otherfileList[i].response.data);
              } else {
                this.otherImg.push(this.logms.otherImgs[i]);
              }
            }
            console.log("this.otherImg", this.otherImg);
          } else {
            this.otherImg = null;
          }
          console.log(this.otherImg);
          const data = {
            interiorImg: this.interiorImg,
            doorImg: this.doorImg,
            otherImgs: this.otherImg,
            regIdentityRequest: {
              id: this.id ? this.id : "",
              identityName: values.identityName,
              type: "",
              identityNo: values.identityNo,
              expiryDate: this.expiryDate,
              imgHead: this.imgHead,
              imgEmblem: this.imgEmblem,
            },
          };
          if (!values.identityName) {
            data.regIdentityRequest = null;
          }
          this.loading = true;
          api.Speupload(
            data,
            (res) => {
              console.log("res", res);
              if (res.code == "OK") {
                this.pass = true;
                // this.$message.info(res.message)
                // 提交成功清缓存
                const data1 = {};
                api.Close(
                  data1,
                  (res) => {
                    console.log("res", res);
                  },
                  (err) => {}
                );
                this.doNext(3);
              } else {
                this.loading = false;
                this.pass = false;
                this.$message.error(res.message);
              }
            },
            (err) => {
              console.log("res", res);
            }
          );
        }
      });
    },
    doNext(step) {
      console.log(step);
      var st = step + 1;
      this.$router.push({
        path: "/SpeCustomer/step" + st,
        query: { pass: this.pass },
      });
    },
    handlePreview(file) {
      console.log("file", file);
      this.previewImage = file.url || file.thumbUrl;
      this.previewVisible = true;
    },
    handlePreview2(file) {
      this.previewImage2 = file.url || file.thumbUrl;
      this.previewVisible2 = true;
    },
    handlePreview3(file) {
      console.log("file", file);
      this.previewImage3 = file.url || file.thumbUrl;
      this.previewVisible3 = true;
    },
    handlePreview4(file) {
      this.previewImage4 = file.url || file.thumbUrl;
      this.previewVisible4 = true;
    },
    handlePreview5(file) {
      this.previewImage5 = file.url || file.thumbUrl;
      this.previewVisible5 = true;
    },
    handleChange({ file, fileList }) {
      let pos = file.name.lastIndexOf(".");
      let lastName = file.name.substring(pos, file.name.length);
      let supportTypes = [".jpeg", ".png", ".jpg"]; // jpeg、 png
      if (supportTypes.indexOf(lastName.toLowerCase()) <= -1) {
        this.$message.error("上传图片仅支持 jpeg、 png 2种格式！");
        return;
      }
      if (file.size / (1024 * 1024) > this.imageSize) {
        this.$message.error(`上传图片大小应小于${this.imageSize}Mb`);
        return;
      }
      console.log("fileList", typeof fileList, fileList);
      this.fileList1 = fileList;
      let obj = fileList[0];
      if (obj.response) {
        console.log(obj.response.data);
        this.doorImg = obj.response.data;
      }
      console.log("this.fileList", typeof this.fileList, this.fileList);
      // 根据服务端返回数据筛选上传成功的文件
      let imgUrls = [];
      fileList.forEach((file) => {
        if (file.response && file.response.code === "0") {
          imgUrls.push(file.response.data.fileInfo.url);
        }
      });
    },
    handleChange2({ file, fileList }) {
      let pos = file.name.lastIndexOf(".");
      let lastName = file.name.substring(pos, file.name.length);
      let supportTypes = [".jpeg", ".png", ".jpg"]; // jpeg、 png
      if (supportTypes.indexOf(lastName.toLowerCase()) <= -1) {
        this.$message.error("上传图片仅支持 jpeg、 png 2种格式！");
        return;
      }
      if (file.size / (1024 * 1024) > this.imageSize) {
        this.$message.error(`上传图片大小应小于${this.imageSize}Mb！`);

        return;
      }
      this.fileList2 = fileList;
      let obj = fileList[0];
      if (obj.response) {
        console.log(obj.response.data);
        this.interiorImg = obj.response.data;
      }
      // 根据服务端返回数据筛选上传成功的文件
      let imgUrls = [];
      fileList.forEach((file) => {
        if (file.response && file.response.code === "0") {
          imgUrls.push(file.response.data.fileInfo.url);
        }
      });
    },
    handleChange3({ file, fileList }) {
      let pos = file.name.lastIndexOf(".");
      let lastName = file.name.substring(pos, file.name.length);
      let supportTypes = [".jpeg", ".png", ".jpg", ".pdf"]; // jpeg、 png
      if (supportTypes.indexOf(lastName.toLowerCase()) <= -1) {
        this.$message.error("上传图片仅支持 jpeg、 png、pdf 3种格式！");
        return;
      }
      if (file.size / (1024 * 1024) > 50) {
        this.$message.error(`上传图片大小应小于50Mb！`);
        return;
      }
      this.otherfileList = fileList;
      console.log(this.otherfileList);
      let obj = fileList[0];
      if (obj.response) {
        console.log(obj.response.data);
        // this.otherImg = obj.response.data;
      }
      // 根据服务端返回数据筛选上传成功的文件
      let imgUrls = [];
      fileList.forEach((file) => {
        if (file.response && file.response.code === "0") {
          imgUrls.push(file.response.data.fileInfo.url);
        }
      });
    },
    handleChange4({ file, fileList }) {
      let pos = file.name.lastIndexOf(".");
      let lastName = file.name.substring(pos, file.name.length);
      let supportTypes = [".jpeg", ".png", ".jpg"]; // jpeg、 png
      if (supportTypes.indexOf(lastName.toLowerCase()) <= -1) {
        this.$message.error("上传图片仅支持 jpeg、 png 2种格式！");
        return;
      }
      if (file.size / (1024 * 1024) > this.imageSize) {
        this.$message.error(`上传图片大小应小于${this.imageSize}Mb！`);
        return;
      }
      this.idfileList1 = fileList;
      let obj = fileList[0];
      if (obj.response) {
        console.log(obj.response.data);
        this.imgHead = obj.response.data;
      }
      // 根据服务端返回数据筛选上传成功的文件
      let imgUrls = [];
      fileList.forEach((file) => {
        if (file.response && file.response.code === "0") {
          imgUrls.push(file.response.data.fileInfo.url);
        }
      });
    },
    handleChange5({ file, fileList }) {
      let pos = file.name.lastIndexOf(".");
      let lastName = file.name.substring(pos, file.name.length);
      let supportTypes = [".jpeg", ".png", ".jpg"]; // jpeg、 png
      if (supportTypes.indexOf(lastName.toLowerCase()) <= -1) {
        this.$message.error("上传图片仅支持 jpeg、 png 2种格式！");
        return;
      }
      if (file.size / (1024 * 1024) > this.imageSize) {
        this.$message.error(`上传图片大小应小于${this.imageSize}Mb！`);
        return;
      }
      this.idfileList2 = fileList;
      let obj = fileList[0];
      if (obj.response) {
        console.log(obj.response.data);
        this.imgEmblem = obj.response.data;
      }
      // 根据服务端返回数据筛选上传成功的文件
      let imgUrls = [];
      fileList.forEach((file) => {
        if (file.response && file.response.code === "0") {
          imgUrls.push(file.response.data.fileInfo.url);
        }
      });
    },
    handleCancel() {
      this.previewVisible = false;
    },
    handleCancel2() {
      this.previewVisible2 = false;
    },
    handleCancel3() {
      this.previewVisible3 = false;
    },
    handleCancel4() {
      this.previewVisible4 = false;
    },
    handleCancel5() {
      this.previewVisible5 = false;
    },
    dateChange(date, dateString) {
      console.log("dateString", dateString);
      this.expiryDate = dateString;
    },
    validateIdentityNo(rule, value, callback) {
      const form = this.form;
      if (value && !/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(value)) {
        callback("您输入的身份证号码格式有误！");
      } else {
        console.log("身份证号码！", value);
      }
      callback();
    },
  },
};
</script>
<style scoped>
.formGroupTitle {
  font-size: 20px;
  font-weight: bold;
  text-align: right;
}

/* .content{
    text-align: center
} */
.card {
  margin-top: 50px;
}

.card .title {
  text-align: center;
  padding: 20px;
  font-size: 18px;
}

.avatar-uploader {
  float: left;
}

.avatar-uploader > .ant-upload {
  width: 128px;
  height: 128px;
}

.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}

.btn-next {
  margin-top: 20px;
}

.btn-style {
  background: #ccc;
  border: 1px solid #ccc;
  color: #eee;
}

.row-sty {
  margin-bottom: 30px;
  margin-top: 20px;
}

.a-sty {
  font-size: 14px;
  color: #1890ff;
}

.submitButton {
  width: 8vw;
}
</style>